import React, { useState, useRef, useContext } from 'react';
import AuthContext from '../contexts/AuthContext';
import { analyzePalm, savePalmAnalysis, getUserPalmAnalyses } from '../services/palmAnalysisService';
import './PalmAnalysis.css';

/**
 * 手相分析页面组件
 */
const PalmAnalysis = () => {
  // 认证上下文
  const { user } = useContext(AuthContext);
  
  // 状态管理
  const [selectedImage, setSelectedImage] = useState(null);
  const [previewUrl, setPreviewUrl] = useState('');
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysisResult, setAnalysisResult] = useState(null);
  const [error, setError] = useState('');
  const [history, setHistory] = useState([]);
  const [activeTab, setActiveTab] = useState('analyze'); // 'analyze' or 'history'
  const [handType, setHandType] = useState('right'); // 'left' or 'right'
  
  // DOM引用
  const fileInputRef = useRef(null);
  
  // 处理图片选择
  const handleImageChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      // 验证文件类型
      if (!file.type.match('image.*')) {
        setError('请选择图片文件');
        return;
      }
      
      // 验证文件大小 (最大5MB)
      if (file.size > 5 * 1024 * 1024) {
        setError('图片大小不能超过5MB');
        return;
      }
      
      setSelectedImage(file);
      setPreviewUrl(URL.createObjectURL(file));
      setError('');
    }
  };
  
  // 触发文件选择
  const triggerFileSelect = () => {
    fileInputRef.current.click();
  };
  
  // 移除已选择的图片
  const removeImage = () => {
    setSelectedImage(null);
    setPreviewUrl('');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };
  
  // 执行手相分析
  const handleAnalyzePalm = async () => {
    if (!selectedImage) {
      setError('请先选择一张手部照片');
      return;
    }
    
    if (!user) {
      setError('请先登录后再进行分析');
      return;
    }
    
    setIsAnalyzing(true);
    setError('');
    
    try {
      // 调用手相分析API
      const response = await analyzePalm(selectedImage, handType);
      
      if (response.success) {
        setAnalysisResult(response.data);
        setActiveTab('result');
      } else {
        setError(response.message || '分析失败，请稍后重试');
      }
    } catch (err) {
      setError(err.message || '分析失败，请稍后重试');
    } finally {
      setIsAnalyzing(false);
    }
  };
  

  
  // 保存分析结果
  const saveAnalysis = async () => {
    if (!analysisResult) return;
    
    if (!user) {
      setError('请先登录后再保存结果');
      return;
    }
    
    try {
      const response = await savePalmAnalysis(analysisResult);
      
      if (response.success) {
        alert('分析结果已保存！');
        // 更新历史记录
        setHistory(prev => [analysisResult, ...prev]);
      } else {
        setError(response.message || '保存失败');
      }
    } catch (err) {
      setError(err.message || '保存失败');
    }
  };
  
  // 获取历史记录
  const fetchHistory = async () => {
    if (!user) {
      setError('请先登录后查看历史记录');
      return;
    }
    
    try {
      const response = await getUserPalmAnalyses();
      
      if (response.success) {
        setHistory(response.data);
      } else {
        setError(response.message || '获取历史记录失败');
      }
    } catch (err) {
      setError(err.message || '获取历史记录失败');
    }
    
    setActiveTab('history');
  };
  
  // 渲染分析结果
  const renderAnalysisResult = () => {
    if (!analysisResult) return null;
    
    return (
      <div className="analysis-result">
        <h2>手相分析报告</h2>
        <div className="result-header">
          <div className="score">分析时间: {new Date(analysisResult.createdAt).toLocaleString()}</div>
          <div className="hand-type">手部类型: {analysisResult.handType === 'right' ? '右手' : '左手'}</div>
        </div>
        
        <div className="result-section">
          <h3>掌型分析</h3>
          <p><strong>{analysisResult.palmShape.type}</strong>: {analysisResult.palmShape.description}</p>
        </div>
        
        <div className="result-section">
          <h3>主要线条</h3>
          <ul>
            {analysisResult.majorLines.map((line, index) => (
              <li key={index}><strong>{line.name}</strong>: {line.description}</li>
            ))}
          </ul>
        </div>
        
        <div className="result-section">
          <h3>性格特质</h3>
          <ul>
            {analysisResult.personalityTraits.map((trait, index) => (
              <li key={index}><strong>{trait.trait}</strong>: {trait.description} (强度: {trait.strength}/10)</li>
            ))}
          </ul>
        </div>
        
        <div className="result-section">
          <h3>综合分析</h3>
          <p>{analysisResult.analysisSummary}</p>
        </div>
        
        <div className="result-section">
          <h3>职业建议</h3>
          <p>{analysisResult.professionalAdvice}</p>
        </div>
        
        <div className="result-section">
          <h3>感情建议</h3>
          <p>{analysisResult.relationshipAdvice}</p>
        </div>
        
        <div className="result-section">
          <h3>健康提示</h3>
          <p>{analysisResult.healthAdvice}</p>
        </div>
        
        <div className="result-section">
          <h3>财运分析</h3>
          <p>{analysisResult.wealthAnalysis}</p>
        </div>
        
        <div className="result-footer">
          <button className="save-btn" onClick={saveAnalysis}>保存结果</button>
        </div>
      </div>
    );
  };
  
  // 渲染历史记录
  const renderHistory = () => {
    return (
      <div className="history-list">
        <h2>历史记录</h2>
        {history.length === 0 ? (
          <p>暂无历史记录</p>
        ) : (
          <ul>
            {history.map((record) => (
              <li key={record.id} className="history-item">
                <div className="history-header">
                  <span className="hand-type">手部类型: {record.handType === 'right' ? '右手' : '左手'}</span>
                </div>
                <div className="analysis-time">分析时间: {new Date(record.createdAt).toLocaleString()}</div>
                <div className="palm-shape">掌型: {record.palmShape?.type || '未知'}</div>
              </li>
            ))}
          </ul>
        )}
      </div>
    );
  };
  
  return (
    <div className="palm-analysis">
      <header className="page-header">
        <h1>手相分析</h1>
        <p>上传您的手部照片，获取详细的手相分析报告</p>
      </header>
      
      <div className="tabs">
        <button 
          className={activeTab === 'analyze' ? 'active' : ''}
          onClick={() => setActiveTab('analyze')}
        >
          手相分析
        </button>
        <button 
          className={activeTab === 'history' ? 'active' : ''}
          onClick={fetchHistory}
        >
          历史记录
        </button>
      </div>
      
      {activeTab === 'analyze' && (
        <div className="analysis-content">
          <div className="upload-section">
            <h2>上传手部照片</h2>
            <div className="hand-type-selector">
              <label>
                <input
                  type="radio"
                  value="right"
                  checked={handType === 'right'}
                  onChange={(e) => setHandType(e.target.value)}
                />
                右手
              </label>
              <label>
                <input
                  type="radio"
                  value="left"
                  checked={handType === 'left'}
                  onChange={(e) => setHandType(e.target.value)}
                />
                左手
              </label>
            </div>
            
            <div className="upload-area" onClick={triggerFileSelect}>
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleImageChange}
                accept="image/*"
                style={{ display: 'none' }}
              />
              {previewUrl ? (
                <div className="image-preview">
                  <img src={previewUrl} alt="手部预览" />
                  <button className="remove-btn" onClick={(e) => { e.stopPropagation(); removeImage(); }}>
                    移除图片
                  </button>
                </div>
              ) : (
                <div className="upload-prompt">
                  <p>点击选择手部照片</p>
                  <p className="hint">建议在光线均匀的环境下拍摄，手心完全张开</p>
                </div>
              )}
            </div>
            
            {error && <div className="error-message">{error}</div>}
            
            <button 
              className="analyze-btn" 
              onClick={handleAnalyzePalm}
              disabled={isAnalyzing || !selectedImage}
            >
              {isAnalyzing ? '分析中...' : '开始分析'}
            </button>
          </div>
          
          {analysisResult && (
            <div className="result-section-container">
              {renderAnalysisResult()}
            </div>
          )}
        </div>
      )}
      
      {activeTab === 'history' && renderHistory()}
    </div>
  );
};

export default PalmAnalysis;